<?php

namespace Modules\Car\Http\Controllers\Api;

use App\Helpers\Constant;
use App\Helpers\NewBaseData;
use App\Helpers\PayTrait;
use App\Helpers\ResponseData;
use App\Models\Car;
use App\Models\Order;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Modules\Car\Entities\CarOrder;
use Modules\Car\Entities\ChangeOrderSourceLog;
use Modules\Car\Entities\Customer;
use Modules\Car\Entities\ForbidLeaseDate;
use Modules\Car\Entities\Maintenance;
use Modules\Car\Entities\RecognizeDrivingLicense;
use Modules\Car\Entities\Service;
use Modules\Car\Http\Requests\Order\OrderRequest;
use Modules\Manager\Entities\Manager;
use App\Models\AttendanceStatistics;

class UserOrderController extends Controller
{
    use NewBaseData,ResponseData,PayTrait;
    public function getOrderStatus($department){
        $data = [];
        $arr = [0,1,5,6,7];
        foreach ($arr as $k=>$i){
            $total = $this->getOrderModel($i,$department);
           if($total>0){
               $data[$k]['status']= $i;
               $data[$k]['total_num'] = $total;
           }
        }
        return array_values($data);
    }
    public function getOrderModel($status,$department=''){
       $model =  CarOrder::query();
       if($status!=2){
           $model = $model->when($department,function($query)use($department){
               return $query->where('department',$department);
           });
       }
        return $model->where('status',$status)
            ->where('process_status','<=',1)->count();
    }
    /**
     * @param Request $request
     * 获取订单数据
     */
    public $req;
    public function getOrderNum(Request $request){
        $department = $request->input('department','');
        $order['status'] = $this->getOrderStatus($department);
        $order['process_status'] = CarOrder::query()
            ->when($department,function($query)use($department){
                return $query->where('department',$department);
            })
            ->where('process_status','>',Constant::PROCESS_INIT)
            ->select('id','process_status',DB::raw('count(id) as total_num'))
            ->groupBy('process_status')
            ->get();
        $order['waitting_confirm'] = CarOrder::query()
            ->where('status',Constant::ORDER_CLOSED)
            ->where('process_status',Constant::PROCESS_INIT)
            ->count();
        $order['service'] = $this->getCarStatus(Constant::CAR_USE_STATUS_REPAIRING);
        $order['maintenance'] = $this->getCarStatus(Constant::CAR_USE_STATUS_MAINTENANCING);
        $order['empty'] = $this->getCarEmpty();
        return $this->success($order);
    }
    protected function getCarEmpty(){
        return RecognizeDrivingLicense::query()
            ->select('id')
            ->where('use_status',Constant::CAR_USE_STATUS_EMPTY)
            ->where('is_used',Constant::CAR_EMPTY)->count();
    }
    protected function getCarStatus($status){
        return RecognizeDrivingLicense::query()
            ->where('use_status',$status)
            ->where('is_used',Constant::CAR_USING)->count();
    }
    /**
     * 用户顾客客户
     * @param Request $request
     * @return mixed
     */
   public function searchCustomer(Request $request){
       $data = Customer::query()
           ->where('username','like','%'.$request->name.'%')
           ->orWhere('truename','like','%'.$request->name.'%')
           ->orWhere('phone',$request->name)
           ->get();
       return $this->success($data);
   }
   //获取小程序用户
   public function searchUser(Request $request){
       $data = User::query()
           ->where('username','like','%'.$request->name.'%')
           ->orWhere('truename','like','%'.$request->name.'%')
           ->orWhere('phone',$request->name)
           ->where('role',0)
           ->where('department',0)
           ->get();
       return $this->success($data);
   }

    /**
     * 获取车系车辆
     * @param Request $request
     * @return mixed
     */
   public function searchCar(Request $request){
       $name = $request->input('name','');
       $data = Car::query()
           ->when($name,function($query)use($name){
               $query->where('name','like','%'.$name.'%');
           })
           ->where('status',Constant::ORDER_CONFIRM)
           ->get();
       return $this->success($data);
   }
//   获取车系不可租日期
   public function getNoLeaseDate(Request $request){
       $car_series_id = $request->car_series_id;
       $data = $this->searchForbitSeries($request->month,$car_series_id);
       $array_cars = $this->searchSeriesCars($car_series_id);
       if(count($data)||count($array_cars)){
           return $this->success([]);
       }
       sort($array_cars);
       $result = [];
       foreach ($data as $key=>$value){
           $second[]= $value;
           $arr = array_column($second,'car_id');
           sort($arr);
           if($array_cars==$arr){
               $result[]=$value['non_lease_date'];
           }
       }
       return $this->success($result);
   }
    //获取不可用车系id array
    protected function searchForbitSeries($month,$car_series_id){
        $cars = ForbidLeaseDate::query()
            ->select('car_id','forbid_date','non_lease_date')
            ->where('month',$month)
            ->where('car_series_id',$car_series_id)
            ->groupBy('forbid_date')->get()->toArray();
        return $cars;
    }
    //获取该车系下所有车辆
    protected function searchSeriesCars($car_series_id){
        return RecognizeDrivingLicense::query()
            ->where('car_series_id',$car_series_id)
            ->pluck('id')->toArray();
    }

    /**
     * 获取车辆id
     * @param Request $request
     * @return mixed
     */
    public function searchSingleCar(Request $request){
        $name = $request->input('name','');
        $car_id = $request->input('car_id','');
        $forbid = $this->getForbitDateCar($request->pre_fetch_time,$request->pre_return_time)??'';
        $data = RecognizeDrivingLicense::query()
            ->when($name,function($query)use($name){
                $query->where('name','like','%'.$name.'%');
            })
            ->when($car_id,function($query)use($car_id){
                $query->where('car_series_id',$car_id);
            })
            ->when($forbid,function($query)use($forbid){
                $query->whereNotIn('id',$forbid);
            })
            ->where('status',Constant::ORDER_CONFIRM)
            ->get();
        return $this->success($data);
    }
    /*
     * 获取车辆数量
     */
    public function searchSingleCarCount(Request $request){
        $name = $request->input('name','');
        $car_series_id = $request->input('car_series_id','');
        $data = RecognizeDrivingLicense::query()
            ->when($name,function($query)use($name){
                $query->where('name','like','%'.$name.'%');
            })
            ->when($car_series_id,function($query)use($car_series_id){
                $query->where('car_series_id',$car_series_id);
            })
            ->where('status',Constant::ORDER_CONFIRM)
            ->where('use_status',Constant::CAR_USE_STATUS_EMPTY)
            ->count();
        return $this->success($data);
    }
    //价格换算
    public function convert(Request $request){
        $this->req = $request;
        // 获取车辆
        $this->car = $this->seriesCar($request->car_series_id);
        // 计算总计
        $data = $this->totalPrice($request);
        // info($this->all_vip_service);
        // info($data);
        $data['vip_service'] = $this->all_vip_service;
        $data['worry_fee'] = $this->all_worry_fee;
        $data['paint_finish'] = $this->all_paint_finish;
        return $this->success($data);
    }

    //强制取消
    public function cancel(OrderRequest $request){
        $order = CarOrder::query()
            ->where('order_sn',$request->order_sn)
            ->first();
        if($order){
            //取消订单排车更新，如果车辆还有其他订单在使用，则不改变在租状态
            $usedorders = CarOrder::query()->where('gear_car_id', $order->gear_car_id)->where('status',5)->whereIn('process_status',[1,2])->count();
            if($usedorders<=1){
                RecognizeDrivingLicense::query()->where('id',$order->gear_car_id)->update(['is_used'=>0]);
            }
            if($order->out_trade_no){
                $total = $order->mini_pay*100;
                $this->miniRefund($order->order_sn,$order->out_trade_no,$total,$total);
            }
            $order->status = Constant::ORDER__MANAGER_CANCLE;
            $order->save();
            // 取消出勤记录
            AttendanceStatistics::query()->where('order_sn',$order->order_sn)->update(['status'=>2]);
            return $this->success('商家取消成功');
        }else{
            return $this->failed('订单不存在',201);
        }
    }
//    退款
    public function refund(OrderRequest $request){
        $order = CarOrder::query()
            ->where('order_sn',$request->order_sn)
            ->where('status',Constant::ORDER_CONFIRM)
            ->first();
        if($order){
            if($order->transaction_id){
                $out_refund_no = 'bt'.Str::random(28).time();
                $result = DB::update('update car_orders set status = ?,out_refund_no = ?  WHERE status = ? and order_sn = ?', [-2,$out_refund_no,2,$request->order_sn]);
                if($result){
                    $data = $this->miniRefund($order->transaction_id,$out_refund_no,$order->total,$order->total);
                    $order->status = Constant::ORDER__MANAGER_CANCLE;
                    $order->save();
                    return $this->success($data);
                }else{
                    return $this->failed('退款失败,请稍后重试',201);
                }
            }else{
                return $this->failed('非微信付款，无法线上退款',201);
            }
        }else{
            return $this->failed('订单不存在',201);
        }
    }

    /**
     * @param Request $request
     * @param Car $car
     * @return mixed
     * 获取空闲车辆
     */
    public function getEmptyCar(Request $request){
        $empty =  RecognizeDrivingLicense::query()
            ->select('id','car_series_id','plate_number')
            ->where('is_used',Constant::CAR_EMPTY)
           ->with('waittingMot','carSeries')->get();
        $waitting_order = CarOrder::query()//Constant::ORDER_CLOSED
//            ->where('status',2)
            ->where('status',Constant::ORDER_CLOSED)
            ->pluck('gear_car_id');
        $waitting  = RecognizeDrivingLicense::query()
            ->select('id','car_series_id','plate_number')
            ->with('carSeries')
            ->whereIn('is_used',$waitting_order)
            ->get();
        //年检车辆
        $mot = RecognizeDrivingLicense::query()
            ->select('id','car_series_id','plate_number')
            ->whereHas('waittingMot',function($query){
               $query->where('end','>',now());
            })->with('waittingMot','carSeries')->get();
//        维修车辆
        $service = RecognizeDrivingLicense::query()
            ->select('id','car_series_id','plate_number')
            ->whereHas('waittingService',function($query){
                $query->where('end','>',now());
            })->with('waittingService','carSeries')->get();
        //        保养车辆
        $Maintenance = RecognizeDrivingLicense::query()
            ->select('id','car_series_id','plate_number')
            ->whereHas('waittingMaintenance',function($query){
                $query->where('end','>',now());
            })->with('waittingMaintenance','carSeries')->get();
        //保险车辆
        $Insurance = RecognizeDrivingLicense::query()
            ->select('id','car_series_id','plate_number')
            ->whereHas('waittingInsurance',function($query){
                $query->where('end','>',now());
            })->with('waittingInsurance','carSeries')->get();

            $result['empty']['data'] = $empty;
            $result['empty']['num'] = count($empty);
            $result['waitting']['data'] = $waitting;
            $result['waitting']['num'] = count($waitting);

            $result['mot']['data'] = $mot;
            $result['mot']['num'] = count($mot);
            $result['service']['data'] = $service;
            $result['service']['num'] = count($service);
            $result['maintenance']['data'] = $Maintenance;
            $result['maintenance']['num'] = count($Maintenance);
            $result['insurance']['data'] = $Insurance;
            $result['insurance']['num'] = count($Insurance);
            return $this->success($result);

    }
    /**
     * 获取维修中的车辆
     */
    public function getServiceCar(Service $service,Request $request)
    {
        $data  = $this->serviceModel(Constant::CAR_USE_STATUS_REPAIRING)
            ->groupBy('car_series_id')->get();
        if($data){
            foreach ($data as $k=>$v){
                $data[$k]['service'] = Service::query()->where('car_id',$v->id)->orderByDesc('id')->first();
            }
        }
        return $this->success($data);
    }

    /**
     * @param Maintenance $maintenance
     * @param Request $request
     * 获取保养中列表
     */
    public function getMaintenance(Maintenance $maintenance,Request $request){
        $data  = $this->serviceModel(Constant::CAR_USE_STATUS_MAINTENANCING)
            //->append('maintenance')
            ->groupBy('car_series_id')->get();
        if($data){
            foreach ($data as $k=>$v){
                $data[$k]['maintenance'] = Maintenance::query()->where('car_id',$v->id)->orderByDesc('id')->first();
            }
        }
        return $this->success($data);
    }
//    待保养车辆列表 小于1000公里数
    public function waitMaintenance(Request $request){
        $size = $request->input('size',10);
        $data = RecognizeDrivingLicense::query()->with(['useOrders'=>function($query){
                $query->select('id','gear_car_id','order_sn','department')->where('status',5)->whereIn('process_status',[1,2]);
            },'waittingMaintenanceLast'])->whereNull('deleted_at')->whereRaw('(last_kilo_mileage-total_mileage) <= ?',[1000])->paginate($size);
        return $data;
        // return DB::table('recognize_driving_licenses')->whereNull('deleted_at')->whereRaw('(last_kilo_mileage-total_mileage) <= ?',[1000])->paginate($size);
    }
//    待大保养，火花塞小于5000公里数
    public function waitearbox(Request $request){
        $size = $request->input('size',10);
        $data = RecognizeDrivingLicense::query()->with(['useOrders'=>function($query){
                $query->select('id','gear_car_id','order_sn','department')->where('status',5)->whereIn('process_status',[1,2]);
            },'waittingMaintenanceLast'])->whereNull('deleted_at')->whereRaw('(last_spark_plug_mileage-spark_plug_mileage) <= ?',[5000])->paginate($size);
        return $data;
        // return DB::table('recognize_driving_licenses')->whereNull('deleted_at')->whereRaw('(last_spark_plug_mileage-spark_plug_mileage) <= ?',[5000])->paginate($size);
    }
    protected function serviceModel($status=null){
        return RecognizeDrivingLicense::query()
            ->select('id','car_series_id','plate_number')
            ->when($status,function($query)use($status){
                $query->where('use_status',$status);
            })
            ->with(['carSeries'=>function($query){
                $query->select('id','name');
            }]);
    }

    /**
     * 车辆改排
     * @param Request $request
     * @return mixed
     */
   public function changeCar(Request $request){
        $order = CarOrder::query()
            ->find($request->order_id);
        if($order){
            $waitCar = RecognizeDrivingLicense::query()
                ->where('is_used',Constant::CAR_EMPTY)
                ->find($request->wait_car_id);
            if(!$waitCar){
                return $this->failed('被排车辆不存在',201);
            }else{
                $car = RecognizeDrivingLicense::query()->find($order->gear_car_id);
                $car->is_used = Constant::CAR_EMPTY;
                $car->use_status = Constant::CAR_USE_STATUS_EMPTY;
                $car->save();
                $waitCar->is_used = Constant::CAR_USING;
                $waitCar->use_status = Constant::CAR_USE_STATUS_USING;
                $waitCar->save();
                $order->gear_car_id = $request->wait_car_id;
                if($request->filled('license')){
                    $order->license = $request->license;
                }
                if($request->filled('car_series_id')){
                    $order->car_series_id = $request->car_series_id;
                }

                $order->save();
                return $this->success('改排成功');
            }
        }else{
            $this->failed('订单不存在',201);
        }

   }

    /**
     * 获取历史订单
     * @param Request $request
     * @return mixed
     */
   public function historyOrder(Request $request){
       $size = $request->input('size',10);
       $data = CarOrder::query()
           ->with('car','gear')
           ->where('status',Constant::ORDER_CLOSED)
           ->where('process_status',Constant::STATISTICS_WAITING)
           ->paginate($size);
       return $this->success($data);
   }
   //修改订单源
   public function changeSource(Request $request){
       $user = $request->user();
       if(!$user){
           return $this->failed('非法用户!');
       }
       if($user->post_id!=Constant::POST_ADMIN){
           return $this->failed('没有权限!');
       }
       $order = CarOrder::query()->where('order_sn',$request->order_sn)->first();
       if(!$order){
           return $this->failed('车辆不存在!');
       }
       $data = [
           'order_sn'=>$request->order_sn,
           'pre'=>$order->source,
           'name'=>$user->username,
           'change_id'=>$user->id,
           'sub'=>$request->source,
       ];
       $order->source = $request->source;
       $order->department = $request->department;
       if($order->save()){
           ChangeOrderSourceLog::query()->create($data);
           $this->success('修改成功!');
       }

   }
   //根据客户id查询订单
   public function getCustomerOrder(CarOrder $model,Request $request){
    //    if(!$request->filled('userid')){
    //        return $this->failed('用户id不存在',201);
    //    }
        if ($request->filled('userid')) {
            $list = $model
                ->with('user','gear','customer','car',"customer",'initCar')
                // ->where('status',6)
                // ->whereIn('process_status',[4,6])
                ->where('status','>', 4)
                ->where('userid',$request->userid)
                ->orderByDesc('id')
                ->get();
        } elseif ($request->filled('customer_id')) {
            $list = $model
                ->with('user','gear','customer','car',"customer",'initCar')
                // ->where('status',6)
                // ->whereIn('process_status',[4,6])
                ->where('status','>', 4)
                ->where('customer_id',$request->customer_id)
                ->orderByDesc('id')
                ->get();
        }
        
       
       return $this->success($list);
   }
   //获取用户订单
   public function getUserOrder(Request $request){
       $user = $request->user();
       $model = $this->searchOrderModel($request);
       if($request->filled('order_sn')){
           $model = $model->where('order_sn','like','%'.$request->order_sn.'%');
       }
       if($request->filled('pick_finish_start')&&$request->filled('pick_finish_end')){
           $model = $model->whereBetween('pick_finish_at',[$request->pick_finish_start,$request->pick_finish_end]);
       }
       if($request->filled('order_operator')){
           $model = $model->where('order_operator',$request->order_operator);
       }
       $size = $request->input('size',10);
       if($user){
               if($user->post_id==1||$user->role==1){
                   if($request->filled('department')){
                       $model = $model->where('department',$request->department);
                   }

                   $list = $model
                       ->where('status',Constant::ORDER_CLOSED)
                       ->where('process_status',Constant::HISTORY_ORDER)
                       ->orderByDesc('return_time')
                       ->paginate($size);
               }else{
                   $list = $model
                       ->where('status',Constant::ORDER_CLOSED)
                       ->where('process_status',Constant::HISTORY_ORDER)
                       ->where('department',$user->department_id)
                       ->orderByDesc('return_time')
                       ->paginate($size);
               }


           return $this->success($list);
       }else{
          return  $this->failed('用户订单不存在！',201);
       }

   }
   //确认更换车辆
    public function cnofirmChangeSeries(CarOrder $order,Request $request){
        $order = $order->find($request->order_id);
        if(!$order){
            return $this->failed('订单不存在',201);
        }
        if($order->change_car_series_id==0){
            return $this->failed('没有待确认订单',201);
        }
        $order->is_change_status  = Constant::CHANGE_AGREE;
        $order->car_series_id = $order->change_car_series_id;
        $order->save();
        return $this->success('确认成功');
    }
    //根据openid 获取客户数据
    public function getCustomer(Request $request){
        if($request->filled('phone')){
            if ($request->filled('openid')) {
                $user = Customer::query()->where('phone',$request->phone)->where('openid',$request->openid)->first();
                if ($user) {
                    return $this->success($user);
                } else {
                    $user = Customer::query()->where('phone',$request->phone)->first();
                    return $this->success($user);
                }
            } else {
                
            }
        }
       if($request->filled('openid')){
           $user = Customer::query()->where('openid',$request->openid)->first();
           if(!$user){
               return $this->success('用户不存在',201);
           }
           if($user&&$user->phone){
               $customer = Customer::query()->where('phone',$user->phone)->first();
               if($customer){
                   return $this->success($customer);
               }else{
                   return $this->success([]);
               }
           }else{
               return $this->success('用户未绑定手机号',201);
           }
       }
    }
    //小程序客户关联
    public function transCustomer(Customer $model,Request $request){
        if($request->filled('openid')){
            $customer = $model->find($request->customer_id);
            if(!$customer){
                return $this->failed('客户不存在',201);
            }
            $customer->phone = $request->phone;
            $customer->openid = $request->openid;
            $customer->save();
            CarOrder::query()->where('userid',$customer->id)->update(['openid'=>$request->openid]);
            if($request->filled('order_sn')){
                CarOrder::query()->where('order_sn',$request->order_sn)->update(['customer_id'=>$request->customer_id,'wx_name'=>$customer->name]);
            }
            // 更新小程序客户信息
            User::query()->where('openid',$request->openid)->update(['customer_id'=>$request->customer_id]);
            return $this->success('关联成功');
        }
    }

    /**
     * 确认订单
     */
    public function confirmOrder(CarOrder $model,Request $request){
       $order = $model->where('order_sn',$request->order_sn)->first();

    }
}
